# 财务月支出统计  flydragon
class Finances::MonthExpenditureService
  delegate :params, :session, :raw, :link_to, :number_to_currency, to: :@view
  include HeiPisService

  #view 视图上下文
  #company 公司
  def initialize(view,company)
    @view = view
    @company = company
  end

  #执行方法 返回值
  def call

    month = params[:month]

    group_info = Finance.where("company_id = :company_id and date_format(setdate,'%Y-%m')=:setdate",{:company_id => @company.id,:setdate => month}).select("sum(amount) as total_amount,finance_type").group(:finance_type)

    data_info = {:income => 0,:expenditure => 0}

    group_info.each do |record|
      data_info[:income] = record.total_amount if record.finance_type == "收入"
      data_info[:expenditure] = record.total_amount if record.finance_type == "支出"
    end

    filter_params = {:company_id => @company.id,:month => month}

    course_reckon = CourseReckon.joins(:studio).where("studios.company_id= :company_id and date_format(course_reckons.created_at,'%Y-%m')=:month",filter_params).sum(:amount)

    data_info[:course_reckon] = (course_reckon||=0).to_f.round(2)
    data_info[:gain_loss] = data_info[:income]-data_info[:expenditure]

    Rails.logger.info "月支出统计信息为:#{data_info.to_json}"

    data_info
  end

end
